package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Semester;
import com.eduadmin.service.ISemesterService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SemesterDataUploadListener extends AnalysisEventListener<Semester> {
    private int count = 1;
    //依赖注入
    private final ISemesterService semesterService;

    public SemesterDataUploadListener(ISemesterService semesterService) {
        this.semesterService = semesterService;
    }

    List<Semester> list = new ArrayList<>();

    @Override
    public void invoke(Semester data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        ++count;
        Semester semester = semesterService.getSemesterByName(data.getSemesterName());
        if (semester == null) {
            list.add(data);
        } else {
            log.info("Excel表中第 " + count + " 行 的学期名称已被使用 ，该行信息没有导入数据库！");
        }
        saveData();
        list.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            semesterService.addSemesters(list);
        }
        log.info("存储数据库成功！");
    }


}
